package com.guan.trend.web;

import java.util.Scanner;

/**
 * @ClassName ProgramDesign1
 * @Author GuanCary
 * @Date 2020/4/27 10:52
 * @Version 1.0
 * Java程序设计第一题
 **/
public class Test {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //利用控制台传参
        System.out.println("请输入第一个参数firstStr");
        String firstStr = scan.nextLine();
        System.out.println("请输入第二个参数secondStr");
        String secondStr = scan.nextLine();
        System.out.println("给定字符串的最大匹配子字符串是==>" + commonString(firstStr, secondStr));
        //关闭控制台
        scan.close();
    }

    public static String commonString(String str1, String str2) {
        //公共字符串
        String comString = "";
        //子字符串
        String subString = "";
        //找到相较长度最短的字符串
        String minString = str1.length() <= str2.length() ? str1 : str2;
        //从最小匹配长度到最大匹配长度开始遍历
        for (int i = 1; i <= minString.length(); i++) {
            //从基于j开始进行字符串的截取
            for (int j = 0; j < minString.length(); j++)//遍历每个长度下的所有字符串
            {
                //限制字符串起始为j,匹配长度为i,限制i+j不大于minString
                if (i + j <= minString.length()) {
                    //截取字符段subString
                    subString = minString.substring(j, j + i);
                    //如果subString被长度较大的字符串所包含,则匹配成功,并将该子串赋值给comString
                    if (str2.contains(subString)) {
                        comString = subString;
                    }
                }
            }
        }
        return comString;
    }

}

